﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Microsoft.Win32;
using System.IO;
using System.Windows.Threading;
using System.Security.Cryptography;
using  System.Collections.ObjectModel;
using PMP;

namespace UserInterface
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool IsPlaying = false;
        bool IsRepeating = false;
        bool IsShuffling = false;
        DispatcherTimer timer = new DispatcherTimer();
        ObservableCollection<MusicFile> SongList = new ObservableCollection<MusicFile>();
        ObservableCollection<MusicFile> QueList = new ObservableCollection<MusicFile>();

        public MainWindow()
        {
            InitializeComponent();
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Interval = new TimeSpan(0,0,0,0,1);
            songListBox.ItemsSource = SongList;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {

            setTimeSlider(playerMediaElement.Position.TotalMilliseconds);
            
        }

        private void playerMediaElement_MediaOpened(object sender, EventArgs e)
        {
            if(playerMediaElement.NaturalDuration.HasTimeSpan)
                timeSlider.Maximum = playerMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
                
        }

        private void playButton_Click(object sender, RoutedEventArgs e)
        {
            Play();
        }

        private void Play()
        {
            if (!IsSongLoaded())
            {
                songListBox.SelectedIndex = 0;
            }

            if (!IsPlaying)
            {
                playerMediaElement.Play();
                playButtonImage.Source = (BitmapImage)FindResource("pause");
                timer.Start();
            }
            else
            {
                playButtonImage.Source = (BitmapImage)FindResource("play");
                playerMediaElement.Pause();
                timer.Stop();
            }
            IsPlaying = !IsPlaying;


        }

        private void Next()
        {
            if (songListBox.SelectedIndex == songListBox.Items.Count - 1)
            {
                songListBox.SelectedIndex = 0;
            }
            else
            {
                songListBox.SelectedIndex++;
            }
        }

        private void Back()
        {
            if (songListBox.SelectedIndex == 0)
            {
                songListBox.SelectedIndex = songListBox.Items.Count - 1;
            }
            else
            {
                songListBox.SelectedIndex--;
            }
        }

        private void LoadSong(int index)
        {
            if (index > -1)
            {
                try
                {
                    songListBox.SelectedIndex = index;
                    MusicFile track = songListBox.SelectedItem as MusicFile;
                    playerMediaElement.Source = new Uri(track.Path);
                    currentSongTextBlock.Text = track.Title;
                    timeSlider.Value = 0;
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Can't find song at index: " + index);
                }
            }
            else
            {
                MessageBox.Show("No song loadet in to PMP");
            }
        }

        private bool IsSongLoaded()
        {
            bool result = false;
            if (playerMediaElement.Source != null)
            {
                result = true;

            }
            return result;
        }

        private int Repeat()
        {
            if (songListBox.SelectedIndex == songListBox.Items.Count - 1)
            {
                return 0;
            }
            else
            {

                return songListBox.SelectedIndex + 1;
            }
        }

        private int ShuffleAll()
        {
            int min = 0;
            int max = songListBox.Items.Count - 1;
            Random rnd = new Random();
            return rnd.Next(min, max);
        }

        private void ShuffleRemaning()
        {
            
        }

        private void GenQue()
        {
            
        }

        private void GetNextSong()
        {
            if (IsRepeating)
            {

                if (IsShuffling)
                {
                    songListBox.SelectedIndex = ShuffleAll();
                }
                else
                {
                    songListBox.SelectedIndex = Repeat();
                }
               
            }
            else
            {

            }

        }

        private void previousButton_Click(object sender, RoutedEventArgs e)
        {
            Back();
        }

        private void nextButton_Click(object sender, RoutedEventArgs e)
        {
            Next();
        }

        private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                playerMediaElement.Volume = (double)volumeSlider.Value;
            }
            catch (Exception)
            {
            }
        }

        private void searchTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            searchTextBox.Clear();
        }

        private void searchTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            searchTextBox.Text = "Search...";
        }

        private void songListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadSong(songListBox.SelectedIndex);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
           
        }

        private void songListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Play();
        }

        private void removeMenuItem_Click(object sender, RoutedEventArgs e)
        {
            songListBox.Items.Remove(songListBox.SelectedItem);
        }

        private void ImportAll()
        {

            string enviromentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            string[] filePaths = Directory.GetFiles(enviromentPath, "*.*", SearchOption.AllDirectories);
            foreach (string filePath in filePaths)
            {
                //MusicFile file = MusicFile.ReadFile(filePath);
                //if (file != null)
                //{
                //    SongList.Add(file);
                //}
            }
        }

        private void ImportAllItem_Click(object sender, RoutedEventArgs e)
        {
            ImportAll();
        }

        private void sittingsMenuItem_Click(object sender, RoutedEventArgs e)
        {
            SittingsWindow SW = new SittingsWindow();
            SW.ShowDialog();
        }

        private void setTimeSlider(double value)
        {
            timeSlider.Value = value;
            timeSlider.SelectionEnd = value;
        }

        private void playerMediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            timeSlider.Maximum = playerMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
        }

        private void timeSlider_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            timer.Stop();
        }

        private void timeSlider_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            int sliderValue = (int)timeSlider.Value;
            timeSlider.SelectionEnd = timeSlider.Value;
            TimeSpan ts = new TimeSpan(0, 0, 0, 0, sliderValue);
            playerMediaElement.Position = ts;
            timer.Start();
        }

        private void ImportMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ImportAll();
        }

        private void repeatButton_Click(object sender, RoutedEventArgs e)
        {
            IsRepeating = !IsRepeating;

            
        }

        private void shuffleButton_Click(object sender, RoutedEventArgs e)
        {
            IsShuffling = !IsShuffling;
        }

        private void GotFocusMenuEvent(object sender, RoutedEventArgs e)
        {
            songListBox.Visibility = Visibility.Visible;
        }

        private void LostFocusMenuEvent(object sender, RoutedEventArgs e)
        {
            songListBox.Visibility = Visibility.Hidden;
        }

        private void exitMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void restartMenuItem_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
            Application.Current.Shutdown();
        }

    }

}
